package com.lyb.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyb.mapper.CategoryMapper;
import com.lyb.pojo.Category;
import com.lyb.pojo.PageData;
import com.lyb.service.CategoryService;
import com.lyb.utils.Result;
import com.lyb.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result queryList() {
        List<Category> categories = categoryMapper.queryList();
        return Result.build(categories, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result queryByPage(Integer page, Integer size, String keyword) {
        PageHelper.startPage(page, size);
        List<Category> categories = categoryMapper.queryByPage(keyword);
        PageInfo<Category> pageInfo = new PageInfo<>(categories);
        PageData pageData = new PageData();
        pageData.setTotal(pageInfo.getTotal());
        pageData.setCategories(pageInfo.getList());

        return Result.build(pageData, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result queryById(Integer id) {
        Category category = categoryMapper.queryById(id);
        return Result.build(category,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result saveCategory(Category category) {
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        categoryMapper.saveCategory(category);
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result updateCategory(Category category) {
        category.setUpdateTime(new Date());
        categoryMapper.updateCategory(category);
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result deleteCategory(Integer id) {
        categoryMapper.deleteCategory(id);
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }
}
